package guowei.guliproduct.product.service.impl;

import guowei.common.constant.ProductConstant;
import guowei.guliproduct.product.dao.AttrAttrgroupRelationDao;
import guowei.guliproduct.product.entity.AttrAttrgroupRelationEntity;
import guowei.guliproduct.product.entity.AttrGroupEntity;
import guowei.guliproduct.product.entity.CategoryEntity;
import guowei.guliproduct.product.service.AttrAttrgroupRelationService;
import guowei.guliproduct.product.service.AttrGroupService;
import guowei.guliproduct.product.service.CategoryService;
import guowei.guliproduct.product.vo.AttrRelationDelVo;
import guowei.guliproduct.product.vo.AttrRespVo;
import guowei.guliproduct.product.vo.Attrvo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import guowei.common.utils.PageUtils;
import guowei.common.utils.Query;

import guowei.guliproduct.product.dao.AttrDao;
import guowei.guliproduct.product.entity.AttrEntity;
import guowei.guliproduct.product.service.AttrService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;


@Service("attrService")
@Slf4j
public class AttrServiceImpl extends ServiceImpl<AttrDao, AttrEntity> implements AttrService {

    @Autowired
    private AttrGroupService attrGroupService;

    @Autowired
    private  AttrAttrgroupRelationService attrAttrgroupRelationService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private AttrAttrgroupRelationDao attrAttrgroupRelationDao;


    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                new QueryWrapper<AttrEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * 初始加载规格参数界面就会加载
     * 根据传来的参数，用AttrRespVo接受，包括单一数据库中不存在需要联表查询的属性
     * @param params
     * @param catId
     * @return
     */
    @Transactional
    @Override
    public PageUtils queryPagrByKeys(Map<String, Object> params, Long catId) {
        String key = (String) params.get("key");
        QueryWrapper<AttrEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("attr_type", ProductConstant.BASE_TYPE.getType());
        IPage<AttrEntity> page = null;
        if(catId == 0){
            if(!StringUtils.isEmpty(key)){
                wrapper.and((obj)->{
                    obj.eq("attr_id",key).or().like("attr_name",key).or().eq("value_select",key);
                });
            }
            page = this.page(new Query<AttrEntity>().getPage(params),
                    wrapper);
        }else {
            wrapper.eq("catelog_id",catId);
            if(!StringUtils.isEmpty(key)){
                wrapper.and((obj)->{
                    obj.eq("attr_id",key).or().like("attr_name",key).or().like("value_select",key);
                });
            }
            page = this.page(new Query<AttrEntity>().getPage(params),
                    wrapper);
        }

        List<AttrEntity> records = page.getRecords();
        List<Object> list = records.stream().map((attrEntity -> {
            AttrRespVo attrRespVo = new AttrRespVo();
            BeanUtils.copyProperties(attrEntity, attrRespVo);

            CategoryEntity byId = categoryService.getById(attrEntity.getCatelogId());
            attrRespVo.setCatelogName(byId.getName());


            AttrAttrgroupRelationEntity one = attrAttrgroupRelationService.getOne(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrEntity.getAttrId()));
            if(one != null) {
                Long attrGroupId = one.getAttrGroupId();
                AttrGroupEntity attrGroup = attrGroupService.getById(attrGroupId);
                String attrGroupName = attrGroup.getAttrGroupName();
                attrRespVo.setGroupName(attrGroupName);
            }
            return attrRespVo;
        })).collect(Collectors.toList());
        PageUtils pageUtils = new PageUtils(page);
        pageUtils.setList(list);
        return pageUtils;
    }

    /**
     * 类似查规格参数 查销售属性
     * @param params
     * @param catId
     * @return
     */
    @Override
    public PageUtils queryPagrByKeysSale(Map<String, Object> params, Long catId) {
        String key = (String) params.get("key");
        QueryWrapper<AttrEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("attr_type",ProductConstant.SALR_TYPE.getType());
        IPage<AttrEntity> page = null;
        if(catId == 0){
            if(!StringUtils.isEmpty(key)){
                wrapper.and((obj)->{
                    obj.eq("attr_id",key).or().like("attr_name",key).or().eq("value_select",key);
                });
            }
            page = this.page(new Query<AttrEntity>().getPage(params),
                    wrapper);
        }else {
            wrapper.eq("catelog_id",catId);
            if(!StringUtils.isEmpty(key)){
                wrapper.and((obj)->{
                    obj.eq("attr_id",key).or().like("attr_name",key).or().like("value_select",key);
                });
            }
            page = this.page(new Query<AttrEntity>().getPage(params),
                    wrapper);
        }
        List<AttrEntity> records = page.getRecords();
        List<Object> list = records.stream().map((attrEntity -> {
            AttrRespVo attrRespVo = new AttrRespVo();
            BeanUtils.copyProperties(attrEntity, attrRespVo);

            CategoryEntity byId = categoryService.getById(attrEntity.getCatelogId());
            attrRespVo.setCatelogName(byId.getName());

            return attrRespVo;
        })).collect(Collectors.toList());
        PageUtils pageUtils = new PageUtils(page);
        pageUtils.setList(list);
        return pageUtils;
    }

    /**
     * 新增关联
     * @param attrRelationDelVos
     */
    @Override
    public void saveRelation(AttrRelationDelVo[] attrRelationDelVos) {
        List<AttrRelationDelVo> asList = Arrays.asList(attrRelationDelVos);
        List<AttrAttrgroupRelationEntity> list = asList.stream().map(attrRelationDelVo -> {
            AttrAttrgroupRelationEntity attrAttrgroupRelationEntity = new AttrAttrgroupRelationEntity();
            BeanUtils.copyProperties(attrRelationDelVo, attrAttrgroupRelationEntity);
            return attrAttrgroupRelationEntity;
        }).collect(Collectors.toList());
        attrAttrgroupRelationService.saveBatch(list);
    }


    /**
     * 将数据保存进数据库只有当是规格参数时才需要建立联系即attr_type=1    并建立联系 attr_attrGroup联系
     * @param attrvo
     */
    @Transactional
    @Override
    public void saveAndRelation(Attrvo attrvo) {
        if(attrvo.getAttrType() == ProductConstant.BASE_TYPE.getType()) {
            AttrEntity attrEntity = new AttrEntity();
            BeanUtils.copyProperties(attrvo, attrEntity);
            this.save(attrEntity);

            AttrAttrgroupRelationEntity attrAttrgroupRelationEntity = new AttrAttrgroupRelationEntity();
            attrAttrgroupRelationEntity.setAttrId(attrEntity.getAttrId());
            attrAttrgroupRelationEntity.setAttrGroupId(attrvo.getAttrGroupId());
            attrAttrgroupRelationEntity.setAttrSort(0);
            if(attrvo.getAttrGroupId() != null) {
                attrAttrgroupRelationService.save(attrAttrgroupRelationEntity);
            }
        } else {
            AttrEntity attrEntity = new AttrEntity();
            BeanUtils.copyProperties(attrvo, attrEntity);
            this.save(attrEntity);
        }
    }

    /**
     * 修改时能够回显 路径以及分组信息 是规格参数时回显groupname  销售参数则不回显
     * 给vo类附上路径，id等信息
     * @param attrvo
     * @return
     */
    @Transactional
    @Override
    public AttrRespVo getByVo(Attrvo attrvo) {
        if(attrvo.getAttrType() == 1) {
            Long catelogId = attrvo.getCatelogId();
            CategoryEntity byId = categoryService.getById(catelogId);

            Long attrId = attrvo.getAttrId();
            AttrAttrgroupRelationEntity attrAttrgroupRelationServiceOne = attrAttrgroupRelationService.getOne(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrId));
            AttrRespVo attrRespVo = new AttrRespVo();
            if(attrAttrgroupRelationServiceOne != null){
                Long attrGroupId = attrAttrgroupRelationServiceOne.getAttrGroupId();
                attrvo.setAttrGroupId(attrGroupId);
                AttrGroupEntity attrGroup = attrGroupService.getById(attrGroupId);
                String attrGroupName = attrGroup.getAttrGroupName();
                attrRespVo.setGroupName(attrGroupName);
            }
            Long[] catelogPath = categoryService.findParentPath(attrvo.getCatelogId());

            BeanUtils.copyProperties(attrvo, attrRespVo);
            attrRespVo.setCatelogPath(catelogPath);
            attrRespVo.setCatelogName(byId.getName());

            return attrRespVo;
        }else {
            Long catelogId = attrvo.getCatelogId();
            CategoryEntity byId = categoryService.getById(catelogId);

            Long[] catelogPath = categoryService.findParentPath(attrvo.getCatelogId());
            AttrRespVo attrRespVo = new AttrRespVo();
            BeanUtils.copyProperties(attrvo, attrRespVo);
            attrRespVo.setCatelogPath(catelogPath);
            attrRespVo.setCatelogName(byId.getName());
            return attrRespVo;
        }
    }

    /**
     * 规格参数修改和销售参数修改时都调用此方法
     * @param attrvo
     */
    @Transactional
    @Override
    public void updatePaths(Attrvo attrvo) {
        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attrvo,attrEntity);
        log.info("attrEntity",attrEntity);
        this.updateById(attrEntity);

        if (attrvo.getAttrType() == 1) {
            Long attrId = attrvo.getAttrId();
            AttrAttrgroupRelationEntity one = attrAttrgroupRelationService.getOne(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrId));
            if (one == null) {
                this.saveAndRelation(attrvo);
            } else {
                one.setAttrGroupId(attrvo.getAttrGroupId());
                attrAttrgroupRelationService.updateById(one);
            }
        }

    }
}